<template>
  <div>
    <a-modal
      title="授权菜单"
      :width="600"
      centered
      :maskClosable="false"
      :destroyOnClose="true"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="formLoading">
        <a-form>
          <a-form-item label="菜单权限" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-tree
              v-if="treeData.length"
              checkable
              :tree-data="treeData"
              :auto-expand-parent="autoExpandParent"
              v-model:checkedKeys="checkedKeys"
              :replaceFields="replaceFields"
              :defaultExpandAll="true"
              @check="onCheck"
            />
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script lang='ts'>
import { defineComponent, PropType, reactive, toRefs, ref, computed, watch, onMounted } from 'vue'
import { sysUserOwnData, sysUserGrantData, getOrgTree } from '@/api/system/user'
import { SysMenuTreeForGrant } from '@/api/system/menu'
import { sysRoleOwnMenu, sysRoleGrantMenu } from '@/api/system/role'
import { useRouter } from 'vue-router'
import { useStore } from '@/store'
import { message } from 'ant-design-vue'
export default defineComponent({
  name: 'userOrgForm',
  components: {},
  emits: ['refresh'],

  setup(props, ctx) {
    const router = useRouter()
    const store = useStore()
    const state = reactive({
      labelCol: {
        style: { 'padding-right': '20px' },
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      expandedKeys: [],
      visible: false,
      confirmLoading: false,
      formLoading: true,
      autoExpandParent: true,
      checkedKeys: [] as any[],
      userEntity: {} as any,
      treeData:[],
      childArr:[] as any[],
      replaceFields: {
        key: 'id'
      }
    })
    onMounted(() => {})
    // 初始化方法
    function init(record) {
      // 清空已选择的
      state.checkedKeys = []
      state.userEntity = record
      state.visible = true
      // 已关联数据
      SysMenuTreeForGrant(null).then(res => {
        state.treeData = res
        //state.formLoading = false

        requestList(res)

        expandedMenuKeys(state.userEntity)
        
      })
    }

    // 递归筛选出来所有的子节点，存放在childArr数组中
    function requestList(data) {
      data &&
        data.map(item => {
          if (item.children && item.children.length > 0) {
            requestList(item.children)
          } else {
            state.childArr.push(item.id)
          }
          return null
        })
      // console.log('子节点', this.childArr)
      // return childArr
    }

    function expandedMenuKeys(record) {
      sysRoleOwnMenu({ id: record.id }).then(res => {
        state.checkedKeys = uniqueTree(res, state.childArr)
        // console.log('checkedKeys', this.selectedKeys)
        state.formLoading = false
      })
    }

    function uniqueTree(uniqueArr, Arr) {
        let uniqueChild:any[] = []
        for (var i in Arr) {
            for (var k in uniqueArr) {
                if (uniqueArr[k] === Arr[i]) {
                    uniqueChild.push(uniqueArr[k])
                }
            }
        }
        // console.log('uniqueChild', uniqueChild)
        return uniqueChild
    }

    function onExpand(expandedKeys) {
      state.expandedKeys = expandedKeys
      state.autoExpandParent = false
    }
    function onCheck(checkedKeys) {
      state.checkedKeys = checkedKeys
    }

    function handleSubmit() {
      state.confirmLoading = true
      sysRoleGrantMenu({ id: state.userEntity.id, grantMenuIdList: state.checkedKeys }).then(
        (res) => {
          message.success('授权成功')
          state.confirmLoading = false
          state.visible = false
          ctx.emit('refresh')
        }
      )
    }
    function handleCancel() {
      // 清空已选择的
      state.checkedKeys = []
      state.visible = false
    }
    return {
      ...toRefs(state),
      init,
      sysUserOwnData,
      onExpand,
      onCheck,
      handleCancel,
      handleSubmit
    }
  }
})
</script>

<style lang='scss' scoped>
</style>